from sqlalchemy.ext.asyncio import create_async_engine, AsyncEngine, async_sessionmaker
from sqlalchemy.ext.asyncio.session import AsyncSession
import typing as T
from fastapi import Depends
import logging

from .Global import configuration
from .Configuration import ApplicationConfig, _DataSourceConfig


def create_engine(configuration: ApplicationConfig):
    datasource: _DataSourceConfig = configuration.datasource
    uri = f"{datasource.dataname}+{datasource.driver}://{datasource.username}:{datasource.password}@{datasource.url}"
    return create_async_engine(
        uri,
        pool_size=datasource.pool_size,
        echo=datasource.echo,
        max_overflow=datasource.max_overflow,
        pool_recycle=datasource.pool_recycle,
        pool_pre_ping=True,
    )


engine: AsyncEngine = create_engine(configuration)

SessionFactory: async_sessionmaker = async_sessionmaker(engine)


async def get_session():
    async with SessionFactory() as session:
        async with session.begin():
            yield session


Session = T.Annotated[AsyncSession, Depends(get_session)]  # 数据库


logging.info("数据库初始化完成...")
